<template>
  <div class="cartContent">
    <Header :textName="textName"></Header>
    <!-- 没登录 -->
    <div v-if="!username">
      <div class="noLogin">
         <img src="./image/youpin.jpg" alt="">
         <div class="title">登录后才能看到购物车商品哦~</div>
         <button><router-link to="/logon">去登录</router-link></button>
      </div>
    </div>

    <div v-else style="padding-top:50px">
      <!-- 顶部 -->
      <header class="cartHeard">
        <span class="youpin">有品</span>
        <button @click="handlerEdit">{{isShow ? '完成' : '编辑'}}</button>

        <!-- <button @click="handlerEdit" v-show="isShow === false">编辑</button>
        <button v-show="isShow === true">完成</button> -->
      </header>
      <!-- 购物列表 -->
      <div class="cartList">
        <!-- 商品 -->
        <ul>
          <li class="cartItem" v-for="(cartI,index) in cartList" :key="cartI.goods_id">
            <!-- 品牌（店铺）名称 -->
            <div class="cartLogoName">
              <van-checkbox class="checkbox-icon" v-model="cartI.checked" checked-color="#ee0a24" @click="handlerChecked(cartI.product_id,cartI.checked)"></van-checkbox>
              <div class="border"><span>有品精选</span></div>
            </div>
            <!-- 每个商品 -->
            <div class="shopItem">
              <van-checkbox class="checkItem-icon" v-model="cartI.checked" checked-color="#ee0a24" @click="handlerChecked(cartI.product_id,cartI.checked)"></van-checkbox>
              <div class="shopRight">
                <img class="shopImg" :src="cartI.list_pic_url"></img>
                <div class="shopInfo">
                  <span class="description">{{cartI.goods_name}}</span>
                  <span class="price">￥{{cartI.market_price}}</span>
                </div>
              </div>
            </div>
            <!-- 控制数量 -->
            <div class="countCtrl">
              <van-field name="stepper">
                <template #input>
                  <!-- @plus="increment()" @minus="decrement()" -->
                  <van-stepper v-model="cartI.number" max="99" @change="onChange(cartI.number,cartI.goods_id,cartI.id,cartI.product_id)" />
                </template>
              </van-field>
            </div>
          </li>
        </ul>
      </div>
      <!-- 精选好物 -->
      <!-- <div class="goodContent">
        <span class="goodTitle">精选好物</span>
        <ul class="goodList">
          <li class="goodItem">
            <img src="" alt="">
            <div class="goodDesc">名称小白电池摄像机</div>
            <div class="price">
              <span class="currentPrice">￥<span>150</span></span>
              <del class="originalPrice">￥<span>200</span></del>
            </div>
          </li>
          <li class="goodItem">
            <img src="" alt="">
            <div class="goodDesc">名称小白电池摄像机</div>
            <div class="price">
              <span class="currentPrice">￥<span>150</span></span>
              <del class="originalPrice">￥<span>200</span></del>
            </div>
          </li>
          <li class="goodItem">
            <img src="" alt="">
            <div class="goodDesc">名称小白电池摄像机</div>
            <div class="price">
              <span class="currentPrice">￥<span>150</span></span>
              <del class="originalPrice">￥<span>200</span></del>
            </div>
          </li>
        </ul>
      </div> -->
      <!-- 底部 -->
      <div class="cartFooter">
        <van-checkbox class="checkAll-icon" v-model="isCheckedAll" @click="isCheckAll" checked-color="#ee0a24"></van-checkbox>
        <span class="allSelected">全选</span>
        <div class="right">
          <span class="totalPrice">合计: <span>￥{{cartTotal.checkedGoodsAmount}}</span></span>
          <span class="preOrder" v-show="isShow===false" v-if="cartTotal.checkedGoodsCount !== 0">去结算({{cartTotal.checkedGoodsCount}})</span>
          <span class="preOrder" v-show="isShow===false" v-else="cartTotal.checkedGoodsCount === 0">去结算</span>
          <span class="preOrder" v-show="isShow===true" @click="handlerCancer" v-if="cartTotal.checkedGoodsCount !== 0">删除所选({{cartTotal.checkedGoodsCount}})</span> 
         <span class="preOrder" v-show="isShow===true" v-else="cartTotal.checkedGoodsCount === 0">删除所选</span>   
  
        </div>
      </div>
    </div>
    
  </div>
</template>

<script>
	// import throttle from 'lodash/throttle'
import debounce from "lodash/debounce";

import Header from "@/components/Header";
import Vue from "vue";
import { Checkbox, CheckboxGroup, Form, Field } from "vant";
import { mapGetters } from "vuex";
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Form);
Vue.use(Field);

export default {
  name: "Cart",
  components: { Header },
  data() {
    return {
      isShow: false, //是否显示完成删除
      username: "", // 用户名
      textName: "购物车", // Header组件中的
      isCheckedAll: false, // 全选的默认是
      number: "1", //步进器中输入框的默认值
      isChecked: "", // 单选  false,0,未选中   true,1,选中
      productIds: "", //商品ID
      checkedList: [], //定义一个新的选中的数组
      goodsId: "", //商品id
    };
  },
  computed: {
    ...mapGetters("cart", ["cartList", "cartTotal"]),
  },
  methods: {
    //全选 点击全选当前购物车商品或者取消全选
    isCheckAll() {
      //将当前是否全选的状态同步给商品选中状态
      this.isChecked = this.isCheckedAll ? 1 : 0;
      //多个商品选中，以字符串拼接product_id，以逗号隔开每一项，如："10, 154, 66"
      let arrId = []; //定义数组用来存储商品ID
      //遍历商品集合 获取商品ID添加到数组中
      this.cartList.every((item) => {
        //添加商品ID到数组中
        return arrId.push(item.product_id);
      });
      //将当前数组转换为后端需要的格式 逗号分割 字符串
      let str = arrId.join(",");
      //调用方法改变状态
      if(str != '') {
      this.handlerChecked(str, this.isChecked);
      }
    },
    //选择某一个商品函数
    async handlerChecked(productId, checked) {
      //如果当前选中则将当前选中转为1 否则0
      //想要变成选中状态则传1，未选中状态传0
      this.isChecked = checked ? 1 : 0;
      //调用后端改变状态方法 进行改变商品选中状态
      await this.$store.dispatch("cart/gethangeChecked", {
        isChecked: this.isChecked,
        productIds: productId,
      });

      // 如果不是全选，且有某个单选的时候
      if (!this.isCheckedAll && checked) {
        // 把productId添加到准备好的数组中
        this.checkedList.push(productId);
        // 如果
      } else if(this.isCheckedAll) {
        this.productIds = productId;
      }else if(!checked) {
        this.checkedList.pop(productId);
      }

      // 定义一个点击选择商品id的集合
      let arrId = [];
      //遍历商品集合 获取商品ID添加到数组中
      this.cartList.every((item) => {
        //添加商品ID到数组中
        if (item.checked) {
          return arrId.push(item.product_id);
        }
      });
      // 判断只有不是全选的时候，选择某个的时候把id添加商品集合中，不选则再删除
      if (!this.isCheckedAll) {
        if (checked) {
          arrId.push(productId);
        } else {
          arrId.pop(productId);
        }
        // 定义购物车数组的长度
        let size = this.cartList.length;
        // 添加的时候不能有相同的，数组去重
        let arrSize = [...new Set(arrId)];
        // console.log(size, arrSize, "aaa");
        if (size === arrSize.length) {
          this.isCheckedAll = true;
        }
      } else {
        if (!checked) {
          this.isCheckedAll = false;
        }
      }
    },
    // 商品步进器
    onChange:debounce(async function (number, goodid, id, productId) {
      // console.log(number, goodid, "222");
      await this.$store.dispatch("cart/getStepperChange", {
        number,
        goodsId: goodid,
        id,
        productId,
      });
    },200),
    // 点击  编辑 变 完成
    handlerEdit() {
      this.isShow = !this.isShow;
      if (this.isShow) {
        this.checkedList = [];
        this.isCheckedAll = false;
        this.isCheckAll();
      }
    },
    // 删除商品
    async handlerCancer() {
      console.log(this.checkedList, "77777");
      if (this.checkedList.length > 0) {
        let str = this.checkedList.join(",");
        this.productIds = str;
      }
      if (this.productIds !== "") {
        console.log(this.productIds, "666");
        this.isShow = !this.isShow;
        await this.$store.dispatch("cart/getDeleteGood", {
          productIds: this.productIds,
        });
      }
    },
  },
  // 获取用户信息
  beforeMount() {
    // 读取缓存数
    let username = localStorage.getItem("username");
    // let avatar=localStorage.getItem('avatar')
    // console.log(username,'用户信息');
    // 判断是否获取到了
    if (username) {
      // 存储用户信息
      this.username = username;
    }
  },
  mounted() {
    this.$store.dispatch("cart/getCartListData");
  },
};
</script>

<style lang="less" scoped>
.cartContent {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  // 没有登录
  .noLogin {
    width: 100%;
    height: 100%;
    background-color: #fff;
    img {
      position: absolute;
      left: 40%;
      top: 30%;
      width: 200px;
      height: 300px;
    }
    .title {
      font-size: 40px;
      position: absolute;
      left: 25%;
      top: 48%;
      color: #a1a1a1;
    }
    button {
      width: 240px;
      height: 100px;
      font-size: 40px;
      color: #a1a1a1;
      border: 1px solid #a1a1a1;
      border-radius: 40px;
      background-color: #fff;
      position: absolute;
      left: 39%;
      top: 53%;
    }
  }
  // 有品
  .cartHeard {
    height: 100px;
    background-color: #f6f6f6;
    display: flex;
    justify-content: space-between;
    padding: 10px 20px;
    // margin-top: 130px;
    .youpin {
      font-size: 50px;
      line-height: 100px;
      font-weight: 700;
      color: #855d3a;
      font-family: "SimSun";
    }
    button {
      width: 170px;
      height: 80px;
      color: #855d3a;
      border: 1px solid #855d3a;
      margin: 10px 20px;
    }
  }
  // 购物车列表
  .cartList {
    height: 100%;
    padding-bottom: 200px;
    .cartItem {
      background-color: #fff;
      height: 330px;
      padding: 10px;
      position: relative;
      margin-bottom: 20px;
      // 店铺名称
      .cartLogoName {
        display: flex;
        position: relative;
        .checkbox-icon {
          position: absolute;
          left: 20px;
          top: 30px;
        }
        .border {
          margin: 10px 20px 0 100px;
          // background-color: pink;
          width: 100%;
          height: 80px;
          border-bottom: 1px solid #a1a1a1;
          span {
            font-size: 42px;
            font-weight: 700;
          }
        }
      }
      // 商品信息
      .shopItem {
        // background-color: pink;
        width: 100%;
        height: 250px;
        position: absolute;
        bottom: 0;
        .checkItem-icon {
          position: absolute;
          left: 20px;
          top: 100px;
        }
        .shopRight {
          display: flex;
          position: absolute;
          top: 25px;
          left: 100px;
          .shopImg {
            width: 200px;
            height: 200px;
          }
          .shopInfo {
            font-size: 28px;
            display: flex;
            flex-direction: column;
            margin: 30px;
          }
          .price {
            margin-top: 20px;
            color: #bb2c08;
          }
        }
      }
      // 控制数量
      .countCtrl {
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }
  }
  // 精选好物
  .goodContent {
    height: 100%;
    background-color: #fff;
    padding: 30px;
    .goodTitle {
      height: 100px;
      display: block;
      font-size: 40px;
      text-align: center;
      line-height: 100px;
    }
    .goodList {
      // background-color: pink;
      display: flex;
      flex-flow: wrap;
      justify-content: space-between;
      box-sizing: border-box;
      // width: 960px;
      .goodItem {
        width: 450px;
        height: 600px;
        img {
          width: 100%;
          height: 80%;
          background-color: #f0f0f0;
        }
        .goodDesc {
          margin: 10px 0;
        }
        .currentPrice {
          span {
            font-size: 45px;
          }
          color: red;
          margin-right: 10px;
        }
        .originalPrice {
          color: gray;
          span {
            font-size: 38px;
          }
        }
      }
    }
  }
  // 底部
  .cartFooter {
    position: fixed;
    display: flex;
    bottom: 130px;
    width: 100%;
    height: 120px;
    line-height: 120px;
    width: 100%;
    background: #fff;
    font-size: 30px;
    .checkAll-icon {
      margin: 0 30px;
    }
    .allSelected {
      font-size: 34px;
    }
    .right {
      position: absolute;
      right: 0;
      .totalPrice {
        display: inline-block;
        span {
          color: #dd1a21;
        }
      }
      .preOrder {
        display: inline-block;
        background-color: #dd1a21;
        width: 225px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        font-size: 34px;
        color: #fff;
        margin-left: 30px;
      }
    }
  }
}
</style>